package com.roshan.strategy.impl;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import com.roshan.dao.UserDAO;
import com.roshan.domain.User;
import com.roshan.exception.EmailAddressAlreadyExistsException;
import com.roshan.exception.UsernameAlreadyExistsException;
import com.roshan.strategy.UserValidationStrategy;
import com.roshan.util.constants.EntityPropertyConstants;
import com.roshan.util.constants.ExceptionMessageConstants;
import com.roshan.util.constants.NamedQueryConstants;

@Component
public class UserValidationStrategyImpl implements UserValidationStrategy {

    @Autowired
    private UserDAO userDAO;

    @Override
    public void validateUser(User user) {

        Assert.notNull(user);
        Assert.notNull(user.getEmail());
        Assert.notNull(user.getSecurityUser());
        Assert.notNull(user.getSecurityUser().getUsername());
        Assert.notNull(user.getSecurityUser().getPassword());

        String email = user.getEmail();

        Map<String, Object> queryParams = new LinkedHashMap<String, Object>();
        queryParams.put(EntityPropertyConstants.EMAIL, email);
        List<User> users = this.userDAO.findByNamedQuery(NamedQueryConstants.RETRIEVE_USER_BY_EMAIL, queryParams);
        if (users != null && !users.isEmpty()) {
            throw new EmailAddressAlreadyExistsException(ExceptionMessageConstants.EMAIL_ADDRESS_ALREADY_EXISTS);
        }

        String username = user.getSecurityUser().getUsername();

        queryParams = new LinkedHashMap<String, Object>();
        queryParams.put(EntityPropertyConstants.USERNAME, username);
        users = this.userDAO.findByNamedQuery(NamedQueryConstants.RETRIEVE_USER_BY_USERNAME, queryParams);
        if (users != null && !users.isEmpty()) {
            throw new UsernameAlreadyExistsException(ExceptionMessageConstants.USERNAME_ALREADY_EXISTS);
        }

    }

}
